package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.fsd.admin.dao.E_WechatDao;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.E_AutoreplyService;
import com.fsd.admin.service.E_WechatService;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.ParametersUtil;
import com.google.gson.Gson;

/**
 * 微信账号管理Service-实现类
 * @author Administrator
 *
 */

@Service("e_wechatServiceImpl")
public class E_WechatServiceImpl extends MainServiceImpl<E_wechat, String> implements E_WechatService {

	private static final Logger log = Logger.getLogger(E_WechatServiceImpl.class);
    private String depict = "微信账号";
    
    @Resource(name = "e_autoreplyServiceImpl")
	private E_AutoreplyService autoreplyService;
	
    @Resource(name = "e_wechatDaoImpl")
   	public void setBaseDao(E_WechatDao e_wechatDao) {
   		super.setBaseDao(e_wechatDao);
   	}
    
	@Resource(name = "e_wechatDaoImpl")
	private E_WechatDao objectDao;
	
	private static final Lock lock = new ReentrantLock();
	
	/**
	 * 设置对象Map集合
	 * @param wxid
	 * @return
	 * @throws Exception
	 */
	private E_wechat getWechatApiidMap(String apiid){
		lock.lock();
		Map<String, E_wechat> objectMap = null;
		String strKey = Config.E_MECHATMAP;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				List<E_wechat> allObjectList = objectDao.queryByHql("from E_wechat t");
				objectMap = new HashMap<String,E_wechat>();
				for (E_wechat obj : allObjectList) {
					objectMap.put(obj.getApiid(), obj);
				}
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, E_wechat>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (objectMap != null && objectMap.containsKey(apiid)){
			return objectMap.get(apiid);
		}
		return null;
	}
	
	/**
	 * 根据ApiID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_wechat getObjectByApiId(String apiid)  throws Exception{
		E_wechat wechat = this.getWechatApiidMap(apiid);
		if (wechat != null){
			return wechat;
		}
		return null;
	}
	
	/**
	 * 根据ID获取微信账号对象，并检查账号完整性
	 * @param wxid
	 * @return
	 * @throws Exception
	 */
	public E_wechat getWeChatCheckInfo(String wxid)  throws Exception{
		E_wechat wechat = objectDao.get(wxid);
		if (wechat == null){
			throw new BusinessException(depict + "信息未找到!");
		}
		if (wechat.getAppid() == null || wechat.getAppid().equals("")){
			throw new BusinessException(depict + "开发者ID信息为空!");
		}
		if (wechat.getAppsecret() == null || wechat.getAppsecret().equals("")){
			throw new BusinessException(depict + "开发者密码信息为空!");
		}
		return wechat;
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public List<E_wechat> getObjectList(ParametersUtil param, A_Employee employee) throws Exception{
		String sql = "from E_wechat where companyid = '" + employee.getCompanyid() + "'";
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				sql += " and name like '" + objectMap.get("name") + "'";
			}
		}
		sql += " order by adddate desc ";
		return objectDao.queryByHql(sql);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_wechat getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_wechat obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 * @param a_employee
	 * @param a_company
	 * @throws Exception
	 */
	public void saveObject(E_wechat obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			long count = objectDao.getCount("apiid = '" + obj.getApiid() + "' and " +
					" id <> '" + obj.getId() + "' ");
			if (count > 0){
				throw new BusinessException(depict + "此访问参数已经存在：“" + obj.getApiid() + "”!");
			}
			E_wechat old_obj = objectDao.get(obj.getId());
			old_obj.setName(obj.getName());
			old_obj.setAccount(obj.getAccount());
			old_obj.setApiid(obj.getApiid());
			old_obj.setAppid(obj.getAppid());
			old_obj.setAppsecret(obj.getAppsecret());
			old_obj.setAccesstoken(obj.getAccesstoken());
			old_obj.setToken(obj.getToken());
			old_obj.setEncodingaeskey(obj.getEncodingaeskey());
			old_obj.setRemark(obj.getRemark());
			old_obj.setUpdatedate(this.getData());
			old_obj.setUpdateemployeeid(employee.getId());
			old_obj.setUpdateemployeename(employee.getRealname());
			objectDao.update(old_obj);
		}else{
			//新增
			long count = objectDao.getCount("apiid = '" + obj.getApiid() + "'");
			if (count > 0){
				throw new BusinessException(depict + "此访问参数已经存在：“" + obj.getApiid() + "”!");
			}
			obj.setId(this.getUUID());
			obj.setCompanyid(employee.getCompanyid());
			obj.setAdddate(this.getData());
			obj.setAddemployeeid(employee.getId());
			obj.setAddemployeename(employee.getRealname());
			objectDao.save(obj);
			autoreplyService.saveInitSystemAutoReply(obj);
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, E_WechatServiceImpl.class);
		EhcacheUtil.getInstance().remove(Config.E_MECHATMAP);
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		objectDao.executeHql("delete from E_wechat t where t.id in (" + ids + ")");
		EhcacheUtil.getInstance().remove(Config.E_MECHATMAP);
	}
	
	/**
	 * 测试自动回复接口
	 * @param parameters
	 */
	public String testMessage(ParametersUtil param) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("content") != null && !"".equals(objectMap.get("content"))){
				E_wechat objWC = this.getObjectByApiId(objectMap.get("apiid").toString());
				E_wechatCoreService coreSerive = new E_wechatCoreService();
				return coreSerive.testMessage(objWC, "fromUserName", "toUserName", objectMap.get("content").toString());
			}
		}
		return "未找到信息";
	}
	
}
